﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Service.Core.DapperWrapper;
using ZilLion.Service.Core.DapperWrapper.SqlServer;
using ZilLion.Service.ZilLionOss.Domain.Entitys;
using ZilLion.Service.ZilLionOss.Domain.Repositorys.Interface;

namespace ZilLion.Service.ZilLionOss.Domain.Repositorys
{
    public class OssUserInfoRepository : SqlServerRespository<OssUserInfoEntity>,
        IOssUserInfoRepository
    {
        public OssUserInfoRepository()
        {
            Context = new OssContext();
        }

        public OssUserInfoEntity GetUserInfo(string username)
        {
            var query = DapperHelper.CreateColSqlByMap<OssUserInfoEntity>();
            return
                GetList(
                    $"SELECT  {query} from [oss_user_info] where username=@username",
                    new {username}).FirstOrDefault();
        }

        public OssUserInfoEntity GetUserInfo(long userid)
        {
            var query = DapperHelper.CreateColSqlByMap<OssUserInfoEntity>();
            return
                GetList(
                    $"SELECT  {query} from [oss_user_info] where userid=@userid",
                    new {userid}).FirstOrDefault();
        }

        public void SaveUserInfo(OssUserInfoEntity entity, UnitOfWork unitOfWork = null)
        {
            if (GetUserInfo(entity.UserId) != null)
                Modify(entity, unitOfWork);
            else
                Add(entity, unitOfWork);
        }

        public IEnumerable<OssUserInfoEntity> GetAllUsers()
        {
            return GetAll();
        }

        public void DeleteUser(long userid, UnitOfWork unitOfWork = null)
        {
            var entity = GetUserInfo(userid);
            Remove(entity, unitOfWork);
        }
    }
}